import pandas as pd
from cmd import Cmd
from model_generator.model_wraper import Trainer, Loader
from executor.executor import Executor
from io_manager.filereader import FileReader

config = {
    'warehousedir': 'dbestwarehouse',
    'verbose': 'True',
    'b_show_latency': 'True',
    'backend_server': 'None',
    'epsabs': 10.0,
    'epsrel': 0.1,
    'mesh_grid_num': 20,
    'limit': 30,
    'csv_split_char': ','
}


class WFEstPrompt(Cmd):
    def __init__(self):
        super(WFEstPrompt, self).__init__()
        self.prompt = 'wfestclient> '
        self.intro = "Welcome to WFEst: a model-based AQP engine! Type exit to exit!"
        self.query = ""

    # print the exit message.
    def do_exit(self, inp):
        '''exit the application.'''
        print("DBEst closed successfully.")
        return True

    # process the query
    def default(self, inp):
        cmds = inp.split(' ')
        cmds_len = len(cmds)
        if cmds[0] == 'create':
            df_name = cmds[1]
            sample_size = int(cmds[2])
            bandwidth = float(cmds[3])
            x_header = cmds[4]
            y_header = None
            if cmds_len > 4:
                y_header = cmds[5]
            Trainer(df_name, sample_size, x_header, y_header, bandwidth=bandwidth).train()

        elif cmds[0] == 'exe':
            df_name = cmds[1]
            mode = cmds[2]
            func = cmds[3]
            x_header = cmds[4]
            y_header = None
            if cmds_len > 5:
                y_header = cmds[5]
            loader = Loader(df_name, x_header, y_header)
            kde = loader.load_kde()
            reg = loader.load_reg()

            x, y, total_size = FileReader(df_name, x_header, y_header).read(order_by=True)
            executor = Executor(y, kde, reg, window_size=10000)
            executor.calculate(func, mode)

    # deal with KeyboardInterrupt caused by ctrl+c
    def cmdloop(self, intro=None):
        print(self.intro)
        while True:
            try:
                super(WFEstPrompt, self).cmdloop(intro="")
                break
            except KeyboardInterrupt:
                # self.do_exit("")
                print("DBEst closed successfully.")
                return True

    do_EOF = do_exit


if __name__ == "__main__":
    p = WFEstPrompt()
    p.cmdloop()
